// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { NumberDivide, DateDiff, FormatnumberZero, Mover, DateStamp } from '@/function.js';

// 视图插件
import {
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
} from 'antd';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Loading from '@/components/Loading/Loading';

// css OR less预编译器
import styles from './All.less';

// 图片

/**
 *  Describe:数据连接
 *  Created by xjc on 2019/5/15
 */

@connect(({ fu, loading }) => ({
  fu,
  loading: loading.models.fuRule,
}))
@Form.create()
class NewTwoStock extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   *  Created by xjc on 2019/5/15
   */

  state = {
    listLoading: false, // 加载状态
    selectedRows: [], // 选择行
    formValues: {
      num: 10,
      page: 1,
    }, // 表格参数
    /* pageValues:{current: 1, pageSize: 10, total: 0}, */
    StocksDetailVisible: false, // modal开关
    OptionVisible: false, // modal开关
    record: {}, // 当前行内容
    searchText: '', // 搜索内容
    columns: [], // 表头处理结果
    currentDataSource: [], // 表剩余数据
  };

  /**
   *  Describe:本地搜索
   *  Created by xjc on 2019/6/4
   */

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 80, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 80 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1880ff' : '#181816', fontWeight: '700' }} />
    ),
    onFilter: (value, record) => {
      if (record[dataIndex] === '股票合计') {
        return true;
      }
      return record[dataIndex] === null
        ? ''
        : record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase());
    },
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => <span>{text}</span>,
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  getColumns() {
    const {
      fu: { stocksFilters },
    } = this.props;
    return [
      /* {
            title: '序号',
            dataIndex: 'p',
          }, */
      {
        title: '股票代码',
        dataIndex: 'stock',
        width: 110,
        align: 'center',
        sorter: (a, b) => {
          const c = [a.stock, b.stock].sort();
          if (c[0] === a.stock) {
            return 1;
          }
          return -1;
        },
        ...this.getColumnSearchProps('stock'),
      },
      {
        title: '涨跌幅',
        dataIndex: 'gain',
        align: 'center',
        width: 90,
        sorter: (a, b) => a.gain - b.gain,
        render: (value, row, index) => {
          return (
            <span style={{ color: value > 0 ? '#389e0d' : '#e1111e' }}>
              {typeof value === 'number' || typeof value === 'string'
                ? `${FormatnumberZero(value, 2).toString()}%`
                : null}
            </span>
          );
        },
        onCell: record => ({
          className: styles.newFunction,
        }),
      },
      {
        title: '涨跌幅/BETA',
        dataIndex: 'gainbeta',
        align: 'center',
        width: 90,
        sorter: (a, b) => a.gainbeta - b.gainbeta,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? FormatnumberZero(value, 2).toString()
                : null}
            </span>
          );
        },
        className: styles.newFunction,
      },
      {
        title: 'ATR',
        dataIndex: 'atr',
        align: 'center',
        width: 80,
        sorter: (a, b) => a.atr - b.atr,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(FormatnumberZero(value, 2).toString())
                : null}
            </span>
          );
        },
        className: styles.newFunction,
      },
      {
        title: '买卖方向',
        dataIndex: 'typename',
        width: 80,
        align: 'center',
        filters: [
          {
            text: '多头',
            value: '多头',
          },
          {
            text: '空头',
            value: '空头',
          },
        ],
        onFilter: (value, record) => {
          if (record.stock === '股票合计') {
            return true;
          }
          if (record.typename !== undefined) {
            return record.typename.indexOf(value) === 0;
          }
        },
      },
      {
        title: '股票敞口',
        dataIndex: 'stockopen',
        align: 'center',
        width: 80,
        sorter: (a, b) => a.stockopen - b.stockopen,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? `${NumberDivide((value * 100).toFixed(2).toString())}%`
                : null}
            </span>
          );
        },
      },
      {
        title: '市值',
        dataIndex: 'costmoney',
        align: 'center',
        width: 100,
        sorter: (a, b) => a.costmoney - b.costmoney,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '成本价',
        width: 80,
        dataIndex: 'costprice',
        align: 'center',
        sorter: (a, b) => a.costprice - b.costprice,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '最新价',
        width: 80,
        dataIndex: 'stockprice',
        align: 'center',
        sorter: (a, b) => a.stockprice - b.stockprice,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },

      {
        title: '股数',
        dataIndex: 'stocknumber',
        align: 'center',
        width: 80,
        sorter: (a, b) => a.stocknumber - b.stocknumber,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '当日盈亏',
        dataIndex: 'thisincome',
        align: 'center',
        width: 100,
        sorter: (a, b) => {
          if (b.stock === '股票合计') {
            return false;
          }
          return a.thisincome - b.thisincome;
        },
        render: (tags, record) => {
          if (record.stock === '股票合计') {
            return (
              <span>
                {typeof tags === 'number' || typeof tags === 'string'
                  ? `${NumberDivide(tags.toString())}/${((tags / record.costmoney) * 100).toFixed(
                      2
                    )}%`
                  : null}
                {}
              </span>
            );
          }
          return (
            <span>
              {typeof tags === 'number' || typeof tags === 'string'
                ? NumberDivide(tags.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '盈亏金额',
        dataIndex: 'allincome',
        width: 100,
        align: 'center',
        sorter: (a, b) => {
          if (b.stock === '股票合计') {
            return false;
          }
          return a.allincome - b.allincome;
        },
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      /*   {
        title: '买入理由',
        dataIndex: 'dscription',
      }, */
      {
        title: '止损价格',
        dataIndex: 'lostprice',
        width: 80,
        align: 'center',
        sorter: (a, b) => a.lostprice - b.lostprice,
        render: (value, row, index) => {
          return (
            <span style={{ color: '#222' }}>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '最高价',
        dataIndex: 'highprice',
        width: 80,
        align: 'center',
        sorter: (a, b) => a.highprice - b.highprice,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '回撤',
        dataIndex: 'withdrawal',
        width: 80,
        align: 'center',
        sorter: (a, b) => a.withdrawal - b.withdrawal,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '开仓时间',
        dataIndex: 'tradedate',
        width: 80,
        align: 'center',
        sorter: (a, b) => DateStamp(a.tradedate) - DateStamp(b.tradedate),
        render: (value, row, index) => {
          return <span>{typeof value === 'string' ? value.split(' ')[0] : ''}</span>;
        },
      },

      {
        title: '同行',
        dataIndex: 'industryinfolist',
        align: 'center',
        width: 120,
        render: (value, row, index) => {
          if (value !== null && typeof value === 'object') {
            const arr = [];
            for (let i = 0; i < value.length; i++) {
              arr[i] = (
                <div>
                  {`${value[i].stock} (`}
                  <span style={{ color: value[i].gain > 0 ? '#389e0d' : '#e1111e' }}>
                    {`${value[i].gain}%`}
                  </span>
                  )
                </div>
              );
            }
            return <div>{arr}</div>;
          }
          return null;
        },
        className: styles.newFunction,
      },
      {
        title: '类型',
        dataIndex: 'stocktype',
        width: 80,
        align: 'center',
        filters: [
          {
            text: '龙头',
            value: '龙头',
          },
          {
            text: 'ETF',
            value: 'ETF',
          },
        ],
        onFilter: (value, record) => {
          if (record.stock === '股票合计') {
            return true;
          }
          if (record.stocktype !== undefined) {
            return record.stocktype.indexOf(value) === 0;
          }
        },
      },
    ];
  }

  handleStandardTableChange = (pagination, filtersArg, sorter, extra) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    this.setState({
      currentDataSource: extra.currentDataSource,
    });
    /* 导入列表数据 */
    dispatch({
      type: 'fu/ChangeStocksPage',
      payload: {
        param: 2,
        currentDataSource: extra.currentDataSource,
      },
      callback: res => {},
    });
  };

  /**
   *  Describe:视图
   *  Created by xjc on 2019/5/15
   */

  render() {
    const {
      loading,
      fu: { newTwoStocks },
    } = this.props;
    const { listLoading, selectedRows, record, StocksDetailVisible, OptionVisible } = this.state;
    let columns = [];
    const stocksList = [];
    if (columns.length === 0 && newTwoStocks.code === 1) {
      columns = this.getColumns();
    }
    return (
      <PageHeaderWrapper title="傅总股票持仓">
        <Card>
          {newTwoStocks.code === 0 ? (
            <Loading />
          ) : (
            <div>
              <div style={{ margin: 8, fontSize: '1rem' }}>
                共计：{this.state.currentDataSource.length - 1}
              </div>
              <StandardTable
                bordered
                selectedRows={selectedRows}
                loading={listLoading}
                data={newTwoStocks}
                columns={columns}
                style={{ tableLayout: 'fixed' }}
                className={styles.TableLayout}
                pagination={false}
                onChange={this.handleStandardTableChange}
                scroll={{ x: 1400, y: 618 }}
                rowClassName={(record, index) =>
                  record.stock === '股票合计' ? styles.statisticssTableBackground : styles.ffffff
                }
              />
            </div>
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;

    /* 导入列表数据 */
    dispatch({
      type: 'fu/GetUBSNoTwoPosition',
      payload: { param: 2, currentDataSource: this.state.currentDataSource },
      callback: res => {
        this.setState({
          currentDataSource: res.list,
        });
      },
    });

    window.reloadData3 = setInterval(() => {
      const { dispatch } = this.props;
      /* 导入列表数据 */
      dispatch({
        type: 'fu/GetUBSNoTwoPosition',
        payload: { param: 2, currentDataSource: this.state.currentDataSource },
        callback: res => {
          if (res.code === 1) {
            message.success('刷新成功');
          } else {
            message.error('刷新失败');
          }
        },
      });
    }, 29000);
  }

  componentWillUnmount() {
    window.clearInterval(window.reloadData3);
  }
}

export default NewTwoStock;
